package com.bruce.spring.http.service.cgroup;

import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;


/**
 * cgroup v1 实现类
 */
public class CgroupV1ProviderWithChannel extends CgroupV1BaseProvider implements Closeable {


    // 仅高频读取的文件复用通道
    private final FileChannel usageChannel;
    private final ByteBuffer usageBuffer = ByteBuffer.allocate(64); // 缓冲区复用

    public CgroupV1ProviderWithChannel() throws IOException {
        // 高频读取：打开并复用CPU使用量文件通道
        this.usageChannel = FileChannel.open(Paths.get(CPU_AcctUsagePath), StandardOpenOption.READ);
    }


    @Override
    public long getCurrentCpuTime() throws IOException {
        // 重置缓冲区
        usageBuffer.clear();
        usageChannel.position(0);

        int bytesRead = usageChannel.read(usageBuffer, 0);
        if (bytesRead <= 0) {
            throw new IOException("CPU使用量文件内容为空");
        }

        usageBuffer.flip();
        byte[] content = new byte[bytesRead];
        usageBuffer.get(content);

        return parseLong(content);
    }


    /**
     * 仅关闭高频读取的通道（初始化读取的文件已自动关闭）
     */
    @Override
    public void close() throws IOException {
        usageChannel.close();
    }


    // 手动解析字节数组为long（比new String(bytes).parseLong()减少对象创建）
    private long parseLong(byte[] bytes) {
        long result = 0;
        for (byte b : bytes) {
            if (b == '\n' || b == '\r') { // 忽略换行符
                continue;
            }
            result = result * 10 + (b - '0');
        }
        return result;
    }

}